package jobhunter.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import jobhunter.security.SecurityContext;
import jobhunter.tool.JpaResultHelper;

import org.springframework.transaction.annotation.Transactional;


@Transactional
@SuppressWarnings("unchecked")
public abstract class GenericRepositoryJpa<T>
{
	@PersistenceContext 
	protected EntityManager em;

	protected Class<T> entityClass;

	public void setEntityClass(Class<T> entityClass) 	{ this.entityClass = entityClass; }

	public void persist(T t) 	{ em.persist(t); }


	public void remove(Long id) 
	{
		if(findById(id)!=null )
			em.remove(findById(id));
	}
	
	public abstract T merge(T t);	
	public abstract void remove(T t);

	public T findById(Long id) 	
	{ 
		return (T) JpaResultHelper.getSingleResultOrNull(em.createQuery("SELECT x FROM "+entityClass.getSimpleName()+" x  WHERE x.id=:id AND x.user =:user")
				.setParameter("id", id).setParameter("user", SecurityContext.getUser()));
	}

	public List<T> findByUser() 
	{
		return (List<T>) em.createQuery("SELECT x FROM "+entityClass.getSimpleName()+" x WHERE x.user=:user ORDER BY x.id")
				.setParameter("user", SecurityContext.getUser()).getResultList();		
	}



}
